<template>
  <div class="container">
    <el-container>
      <el-aside width="200px">
        <el-menu :default-openeds="['1', '3']" style="border-right: none">
          <div class="head-container">
            <el-input
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入部门名称"
              v-model="filterText"
              style="margin: 20px 0 20px 0"
              clearable>
            </el-input>
          </div>
          <div class="head-container">
            <el-tree
              @node-click="getNodes"
              node-key="id"
              class="filter-tree"
              :data="deptData"
              :props="defaultProps"
              default-expand-all
              :filter-node-method="filterNode"
              :isDisabled="flagStatus"

              ref="tree">
            </el-tree>
          </div>
        </el-menu>
      </el-aside>
      <el-container>
        <el-main>
          <el-form
            v-show="showSearch"
            ref="queryForm"
            :inline="true"
            :model="formInline"
            size="small"
            class="demo-form-inline"
          >
            <el-form-item label="用户昵称">
              <el-input
                v-model="formInline.userName"
                placeholder="请输入用户昵称"
                clearable/>
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input
                v-model="formInline.phonenumber"
                placeholder="请输入手机号码"
                clearable
              />
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select
                v-model="formInline.status"
                placeholder="用户状态"
                clearable
                style="width: 240px"
              >
                <el-option label="正常" value="0"/>
                <el-option label="停用" value="1"/>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="formInline.createTime"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
              >新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
              >修改
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete">删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="info"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
              >导入
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
              >导出
              </el-button>
            </el-col>
            <right-toolbar :show-search.sync="showSearch" @queryTable="loadUsersList"/>
          </el-row>

          <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="userList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="用户编号" prop="userId" width="120"/>
            <el-table-column label="用户名称" prop="userName" width="120"/>
            <el-table-column label="用户昵称" prop="nickName" width="120"/>
            <el-table-column label="部门" prop="deptName" width="120"/>
            <el-table-column label="手机号码" prop="phonenumber" width="120"/>
            <el-table-column label="状态" align="center">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :disabled="!(scope.row.userName === currUser)" content="当前登录用户禁止停用！"
                            placement="top">
                <el-switch
                  :disabled="scope.row.userName === currUser"
                  v-model="scope.row.status"
                  active-value="0"
                  inactive-value="1"
                  @change="handleStatusChange(scope.row)"
                />
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding " width="200px">
              <template v-if="scope.row.roleId !== 1" slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
                </el-button>
                <el-dropdown trigger="click" size="mini">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-d-arrow-right el-icon--right"
                    @click="handleMore(scope.row)"
                  >更多
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item icon="el-icon-key" @click.native="updatePassword(scope.row)">重置密码</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-circle-check" @click.native="allocation(scope.row )">分配角色
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <!--          分页 开始-->
          <el-pagination
            :current-page="current"
            :page-sizes="[2, 5, 10, 20, 40]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <!--表格数据-->
          <el-button type="text" @click="dialogFormVisible = true"/>
          <el-dialog :title="this.formTile" :visible.sync="dialogFormVisible">
            <el-form ref="userForm" :model="userForm" label-width="80px" :rules="rules" class="demo-ruleForm" >
              <el-row>
                <el-col :span="12">
              <el-form-item label="用户昵称" style=" display: inline-block;width:300px" prop="nickName">
                <el-input v-model="userForm.nickName" placeholder="请输入用户" />
              </el-form-item>
                </el-col>
                <el-col :span="12">
              <el-form-item label="用户性别" style="display: inline-block;margin-left: 50px;width:350px">
                <el-select v-model="userForm.sex" placeholder="请选择性别">
                  <el-option label="男" value="0"></el-option>
                  <el-option label="女" value="1"></el-option>
                  <el-option label="未知" value="2"></el-option>
                </el-select>
              </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="归属部门"  style="width:650px" prop="parentId">
                <treeselect
                  v-model="userForm.deptId"
                  placeholder="请选择部门"
                  :options="menuOptions"
                  :normalizer="normalizer"
                  :show-count="true"
                />
              </el-form-item>

              <el-form-item label="手机号码" style="display: inline-block;width:300px"  prop="phonenumber" >
                <el-input v-model="userForm.phonenumber" placeholder="请输入联系电话"/>
              </el-form-item>
              <el-form-item label="邮箱" style="display: inline-block;margin-left: 50px;width:300px" prop="email">
                <el-input v-model="userForm.email" placeholder="请输入邮箱"/>
              </el-form-item>
              <el-row>
                <el-col :span="12">
              <el-form-item label="用户名称" style="display: inline-block;width:300px"  prop="userName" v-if="userForm.userId == '-1'">
                <el-input v-model="userForm.userName" placeholder="请输入用户名称"/>
              </el-form-item>
                </el-col>
                <el-col :span="12">
              <el-form-item label="用户密码" style="display: inline-block;margin-left: 50px;width:300px" prop="password" v-if="userForm.userId == '-1'">
                <el-input  show-password v-model="userForm.password" />
              </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
              <el-form-item label="岗位" style="display: inline-block;margin-left: 50px;width:350px">
                <el-select v-model="userForm.sex" placeholder="请选择岗位">
                  <el-option label="董事长" value="0"></el-option>
                  <el-option label="项目经理" value="1"></el-option>
                  <el-option label="人力资源" value="2"></el-option>
                  <el-option label="普通员工" value="3"></el-option>
                </el-select>
              </el-form-item>

                </el-col>
                <el-col :span="12">
              <el-form-item label="角色" style="display: inline-block;margin-left: 50px;width:350px">
              <el-select
                v-model="userForm.roleIds"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择角色">
                <el-option label="超级管理员" value="0"></el-option>
                <el-option label="普通角色" value="1"></el-option>
              </el-select>
              </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
              <el-form-item label="状态" style="display: inline-block">
                <el-radio-group v-model="userForm.status">
                  <el-radio label="0" value="0">正常</el-radio>
                  <el-radio label="1" value="1">停用</el-radio>
                </el-radio-group>
              </el-form-item>
                </el-col>
                <el-col :span="12">
              <el-form-item label="备注"  style="display: inline-block;margin-left: 140px" prop="remark">
                <el-input v-model="userForm.remark" type="textarea" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
            </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="save('userForm')">确定</el-button>
              <el-button type="danger" @click="resetForm('userForm')">关闭</el-button>
            </div>
          </el-dialog>

          <!-- 用户导入对话框 -->
          <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload
              ref="upload"
              :limit="1"
              accept=".xlsx, .xls"
              :action="upload.url"
              :disabled="upload.isUploading"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :auto-upload="false"
              drag
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip text-center" slot="tip">
                <span>仅允许导入xls、xlsx格式文件。</span>
                <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                         @click="importTemplate">下载模板
                </el-link>
              </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = false">取 消</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
    import {parseTime} from '../../../utils'
    import {getToken} from "../../../utils/auth";
    import Treeselect from '@riophae/vue-treeselect'
    import * as router from "vue-router";
    import '@riophae/vue-treeselect/dist/vue-treeselect.css';
    import {getInfo} from "../../../api/user";
    import '@riophae/vue-treeselect/dist/vue-treeselect.css'
    import { checkInfo } from "@/api/user";
    import store from "@/store";

    export default {
        components: {Treeselect},
        name: 'index',
        watch: {
            filterText(val) {
                this.$refs.tree.filter(val);
            },

        },
        data() {
            const validatePhone = (rule, value, callback) => {
                console.log(value)
                const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
                const reg = '*';
                if (value === '') {
                    callback(new Error('请输入手机号'));
                } else if (!regMobile.test(value) && reg !== (value.slice(4, 5))) {
                    callback(new Error('手机号码不正确!'));
                } else {
                    callback();
                }
            };
            const validateName = async (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请输入用户名'));
              } else {
                let res = await checkInfo(value)
                if (res.data) {
                  callback(new Error('用户名已存在'));
                } else {
                  callback();
                }
              }
            };
            return {
                rules:{
                    nickName:[
                        { required: true, message: '请输入用户昵称', trigger: 'blur' },
                        { min: 1, max: 5, message: '长度在1到 5 个字符', trigger: 'blur' }
                    ],
                    phoneNumber: [
                        { required: true,validator: validatePhone, trigger: 'change' },
                        {min: 11, max: 11, message: '手机号长度不正确！', trigger: ['blur', 'change']}
                    ],
                    email:[
                        { required: true, message: '请输入邮箱', trigger: 'change' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                    password:[
                        { required: true, message: '请输入密码', trigger: 'change' },
                        {  min: 5, max: 10, message: '长度在5到 10 个字符', trigger: ['blur', 'change'] }
                    ],
                  userName:[
                    { required: true, validator: validateName, trigger: 'blur' },
                    { min: 1, max: 5, message: '长度在1到 5 个字符', trigger: 'blur' }
                  ],
                },
                currUser: store.getters.name,
                refreshTable: true,
                isExpandAll: false,
                statusOptions: [], // 状态选项
                loading: true,  //遮罩层
                ids: [], // 选中数组
                single: true, // 非单个禁用
                multiple: true, // 非多个禁用
                showSearch: true,// 显示搜索条件
                filterText: '',//搜索部门名称
                title: '',
                value1: '', // 时间
                userList: [],//用户数据
                current: 1, // 当前页数
                size: 5, // 当前条数
                total: 5, // 总条数
                userForm: {
                    userId: '-1',
                    nickName: '',
                    deptId: '',
                    phoneNumber: '',
                    email: '',
                    createBy: '',
                    userName: '',
                    password: '123456',
                    status: '0',
                    remark: '',
                    roleIds:[]
                },
                dialogFormVisible: false,
                menuOptions: [],
                formTile: '',
                formInline: {
                    userId:'',
                    userName: '',
                    phonenumber: '',
                    status: '',
                    ceateTime: '',
                    deptId:''
                },
                deptFlag:'',
                flagStatus:false,

                deptData: [],  //部门树形数据
                defaultProps: {
                    children: 'depts',
                    label: 'deptName',
                    disabled:function (data,node) {
                        console.log(data)
                        console.log(node)
                        if(data.status == 1){
                            this.flagStatus = true

                        }
                    }
                },

                // 用户导入参数
                upload: {
                    // 是否显示弹出层（用户导入）
                    open: false,
                    // 弹出层标题（用户导入）
                    title: "",
                    // 是否禁用上传
                    isUploading: false,
                    // 是否更新已经存在的用户数据
                    updateSupport: 0,
                    // 设置上传的请求头部
                    headers: {Authorization: "Bearer " + getToken()},
                    // 上传的地址
                    url: "/sysUser/import?Authorization=" + getToken()
                },
            }
        },

        methods: {

          //获取当前节点信息(左侧菜单与分页显示联动)
          getNodes(node, e) {
            console.log(node)
            this.formInline.deptId = node.deptId;
            this.formInline.userId = '';
            console.log(this.formInline)
            this.loading = true;
              console.log(this.formInline)
              // 分页数据
              this.axios.get('/sysUser/page?' + this.qs.stringify(this.formInline),
                  {
                      params: {
                          current: this.current,
                          size: this.size
                      }
                  }).then(result => {
                  // 处理后台数据(将后台result.data数据与userList集合绑定)
                  this.userList = result.data.data.records;
                  this.total = result.data.data.total;

              });

              console.log(this.formInline)
              //新增 菜单树 数据
              this.axios.get('/sysDept/deptTree/',{
                  params:this.formInline
              }).then(res => {

              })


              this.loading = false;


          },

          //左侧部门树的显示
          filterNode(value, data) {
            console.log(data);
            if (!value) return true;
            return data.deptName.indexOf(value) !== -1;
          },

          // 转换树结构
          normalizer(node) {
            if (node.depts && !node.depts.length) {
              delete node.depts;
            }
            if (node.deptName == null) {
              node.deptName = "请选择部门"
            }
            console.log(node)
            return {
              id: node.deptId,
              label: node.deptName,
              children: node.depts,

            };
          },
          // 折叠菜单
          toggleExpandAll() {
            this.refreshTable = false
            this.isExpandAll = !this.isExpandAll
            this.$nextTick(() => {
              this.refreshTable = true
            })
          },
          // 修改(数据回显)
          handleUpdate(row) {
            this.reset();
            this.dialogFormVisible = true
            this.formTile = '修改用户'
            this.userForm.updateBy = this.userName
            // this.userForm.parentId = row.deptId
            this.userForm = this.qs.parse(this.qs.stringify(row)) // 将row对象解析后赋值给表单对象

          },
          handleAdd() {
            this.formTile = '添加用户'
            this.dialogFormVisible = true
          },

            // 加载页面数据
            async loadUsersList(current) {
                this.loading = true;
                let res = await getInfo(getToken())
                this.formInline.userId = res.data.info.userId
                console.log(this.formInline)
                // 分页数据
                this.axios.get('/sysUser/page?' + this.qs.stringify(this.formInline),
                    {
                        params: {
                            current: this.current,
                            size: this.size
                        }
                    }).then(result => {
                    // 处理后台数据(将后台result.data数据与userList集合绑定)
                    this.userList = result.data.data.records;
                    this.total = result.data.data.total;

                });

                console.log(this.formInline)
                //新增 菜单树 数据
                this.axios.get('/sysDept/deptTree/',{
                    params:this.formInline
                }).then(res => {
                    console.log(res)
                    this.deptData = res.data.data
                    this.menuOptions = res.data.data

                })


                this.loading = false;

            },
            /** 搜索按钮操作 */
            handleQuery() {

                this.loadUsersList(this.current);
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.formInline = {
                    userName: '',
                    phonenumber: '',
                    status: '',
                    ceateTime: ''
                };
                this.handleQuery();
            },

            // 保存按钮
            save(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        // 新增
                        if (this.userForm.userId == -1) {
                            // 新增
                            console.log(this.userForm);
                            this.userForm.userId = '';
                            this.axios.post('/sysUser/add', this.userForm
                            ).then(result => {
                                console.log(result.data);
                                if (result.data.data == '添加成功') {
                                    this.$message({
                                        message: '添加成功',
                                        type: 'success',
                                        duration: 2000, // 显示时间, 毫秒。

                      });
                      this.resetForm(formName);
                      this.loadUsersList(this.current) // 加载页面

                    }
                  })
                } else {
                  // 修改
                  console.log(this.userForm);
                  this.userForm.password = '';
                  this.axios.put('/sysUser/update', {
                      data:this.userForm
                  }
                  ).then(result => {
                    console.log(result.data)
                    if (result.data.data == '修改成功') {
                      this.$message({
                        message: '修改成功',
                        type: 'success',
                        duration: 2000 // 显示时间, 毫秒。
                      });

                      this.loadUsersList(this.current) // 加载页面
                    }
                  })
                }
                // 清除表单数据
                this.clear();
                // 关闭表单
                this.dialogFormVisible = false
              }
            })
          },
          // 关闭表单
          resetForm(userForm) {
            // 清空规则
            this.$refs.userForm.clearValidate();
            this.dialogFormVisible = false;
            this.clear()
          },
          clear() {
            this.userForm = {
              userId: '-1',
              nickName: '',
              deptId: '0',
              parentId: '0',
              phoneNumber: '',
              email: '',
              createBy: '',
              userName: '',
              password: '',
              status: '0',
              remark: '',
              roleId:''
            }
          },



            //更多
            handleMore() {

            },
            // 角色状态修改
            async handleStatusChange(row) {
              if (row.userName === store.getters.name && row.status === '1') {
                this.$message.error('当前登录用户禁止停用！')
              } else {
                const text = row.status == '0' ? '启用' : '停用'
                this.userForm = row
                const {data: res} = await this.axios.put('/sysUser/update', this.userForm)
                if (res.status !== 'OK') {
                  return this.$message.error('失败')
                }
                this.$message.success(text + '成功')
              }
            },
            // 模糊查询提交按钮
            onSubmit() {
                this.loading = true
                // 将日期转换为字符串
                if (this.value1[0] != null) {
                    this.formInline.startTime = parseTime(this.value1[0]).slice(0, 10)
                    this.formInline.endTime = parseTime(this.value1[1]).slice(0, 10)
                }

                this.loadUsersList(this.current)
                this.value1 = ''
            },
            // 重置按钮
            reset() {
                this.formInline = {
                    UserName: '',
                    phonenumber: '',
                    status: '',
                    createTime: '',
                    deptId:''
                },
                    this.value1 = ''
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`)
                this.size = val
                this.loadUsersList(this.current)
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`)
                this.current = val
                this.loadUsersList(this.current)
            },

            //导出
            handleExport() {
                window.open("http://localhost:8080/sysUser/export?Authorization=" + getToken(), "_parent");
            },
            /* 格式化时间*/
            parseTime(time) {
                var date = new Date(time)
                return parseTime(date)
            },
            //
            allocation(row) {
                this.$router.push("/system/user/role/" + row.userId);
            },
          updatePassword(row){
            this.$confirm('是否确认重置密码？ 密码为123456', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                  this.axios.put('http://localhost:8080/sysUser/updatePassword').then(res => {
                  this.loadUsersList(this.current);
                  this.$message({

                    type: 'success',
                    message: '重置成功'
                  });
                });
              })
              .catch(() => {
                console.log("重置失败")

              });
          },


            // 多选框选中数据
          // eslint-disable-next-line vue/no-dupe-keys
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.userId)
                this.single = selection.length != 1
                this.multiple = !selection.length
            },

            /*删除按钮操作*/
            handleDelete(row) {
                const userIds = row.userId || this.ids;
                console.log(userIds);
                this.$confirm('是否确认删除字典编号为"' + userIds + '"的数据项？', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        this.axios.delete("/sysUser/" + userIds).then(res => {
                            this.loadUsersList(this.current);
                            this.$message({
                                type: 'success',
                                message: '删除成功'
                            });
                        });
                    })
                    .catch(() => {
                        console.log("删除失败")
                    });
            },
            /*导入*/
            handleImport() {
                this.upload.title = "用户导入";
                this.upload.open = true;
            },
            /* 下载模板操作 */
            importTemplate() {
                window.open("http://localhost:8080/sysUser/downloadTemp?Authorization=" + getToken(), "_parent");
            },
            // 文件上传中处理
            handleFileUploadProgress(event, file, fileList) {
                this.upload.isUploading = true;
            },
            // 文件上传成功处理
            handleFileSuccess(response, file, fileList) {
                this.upload.open = false;
                this.upload.isUploading = false;
                this.$refs.upload.clearFiles();
                this.loadUsersList(this.current);
            },
            // 提交上传文件
            submitFileForm() {
                console.log("提交")
                this.$refs.upload.submit();
            }
        },
        created() {
            this.loadUsersList(this.current);
        }
    }
</script>

<style scoped>
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

  .el-aside {
    color: #333;
  }
</style>
